import $env from '@/env'

import adminConfig from '@/admin.config.js'
export default {
  namespaced: true,
  state: {
    token: uni.getStorageSync('user_token'),
    tokenExpired: uni.getStorageSync('user_token_expired'),
    userInfo: {},
    userNick:"",
    userMenuList: []
  },
  getters: {
    isTokenValid(state) {
      return state.token && state.tokenExpired > (Date.now() / 1000)
    },
    token(state) {
      return state.token;
    }
  },
  mutations: {
    SET_TOKEN: (state, {
      token,
      tokenExpired
    }) => {
      state.token = token
      state.tokenExpired = tokenExpired
      uni.setStorageSync('user_token', token)
      uni.setStorageSync('user_token_expired', tokenExpired)
    },
    REMOVE_TOKEN: (state) => {
      state.token = ''
      state.tokenExpired = 0
      state.userInfo = {}
      uni.removeStorageSync('user_token')
      uni.removeStorageSync('user_token_expired')
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
      state.userNick = userInfo.nick
    },
    SET_USER_MENU_LIST: (state, menuList) => {
      function traverseTree(menus) {
        menus.forEach(menu => {

          menu.to = menu.url;

          if (menu.to === "/") {
            menu.to = config.index.url;
          }

          if (menu.param) {
            menu.to += "?" + menu.param;
          }


          if (menu.type == 'menu_link') {

            if (menu.url.indexOf('http') == -1) {
              menu.to = "/" + menu.to;
            }

            menu.to = $env.PROJECT_DOMAIN + menu.to;


            menu.to = "/pages/common/webview/webview?target=" + menu.target + "&url=" + encodeURIComponent(menu
              .to);
          }

          menu.name = menu.title;


          // 递归处理子节点
          if (menu.children && menu.children.length > 0) {
            traverseTree(menu.children)
          }
        });
      }
      traverseTree(menuList)
      state.userMenuList = menuList;
    }
  },
  actions: {
    getLastUsername() {
      return uni.getStorageSync('lastUsername');
    },
    login({
      commit,
      dispatch
    }, data) {
      return uni.request({
        url: 'unify/user/login',
        data
      }).then(data => {
        commit('SET_TOKEN', {
          token: data.token,
          tokenExpired: data.expired
        })
        dispatch('init')
      })
    },
    logout({
      commit
    }) {
      uni.showLoading({
        title: "登出中...",
        mask: true
      });
      uni.request({
        url: '/unify/user/logout'
      })

      commit('REMOVE_TOKEN')

      uni.showToast({
        title: "已完成登出账户",
        mask: true
      });

      setTimeout(() => {
        uni.redirectTo({
          url: adminConfig.login.url
        })
      }, 100);

    },
    init({
      commit,
      getters
    }) {
      return new Promise((resolve, reject) => {
        if (!getters.isTokenValid) {
          reject()
          return;
        }
        return uni.request({
          url: '/unify/user/current',
        }).then(data => {
          commit('SET_USER_INFO', data)
          commit('SET_USER_MENU_LIST', data.menuList)
          resolve(data)
        })
      })
    },
    list(_, data) {
      return uni.request({
        url: "/unify/user/index",
        data
      })
    },
    form(_, data = {}) {
      return uni.request({
        url: '/unify/user/form',
        data
      })
    },
    save(_, data = {}) {
      return uni.request({
        url: `/unify/user/${data.id?'update':'save'}`,
        data
      })
    },
    status(_, data) {
      return uni.request({
        url: '/unify/user/status',
        data
      })
    },
    edit(_, data) {
      return uni.request({
        url: '/unify/user/edit',
        data
      })
    },
    read(_, data) {
      return uni.request({
        url: '/unify/user/read',
        data
      })
    },
    delete(_, data) {
      return uni.request({
        url: '/unify/user/delete',
        data
      })
    },
    updateField(_, data) {
      return uni.request({
        url: '/unify/user/updateField',
        data,
      })
    },
    updatePassword(_, data) {
      return uni.request({
        url: "/unify/user/updatePassword",
        data
      })
    }
  }
}